<template>
    <div class="login-container">
        <div class="login-card">
            <div class="login-header">
                <div class="login-header-one">
                    <van-nav-bar left-text="X"  right-text="帮助" @click-left="onClickLeft" @click-right="onClickRight"></van-nav-bar>
                </div>
                <div class="login-header-two">
                    <h3 class="title">您好，请先登录</h3>
                    <p class="subtitle">未注册的手机号登录成功后将自动创建万师傅账户</p>
                </div>
            </div>
            <div class="login-body">
                <van-nav-bar title="系统登录" />
                <van-form @submit="handleLogin" v-model="loginForm">
                    <van-cell-group inset>
                        <van-field autocomplete="current-userAccount" v-model="loginForm.userAccount" label="用户名"
                            placeholder="用户名" :rules="[
                                { required: true, message: '请填写用户名' },
                                { pattern: /^.{2,10}$/, message: '用户名在2到10字符之间' },
                            ]" />
                        <van-field autocomplete="current-userPwd" v-model="loginForm.userPwd" type="password"
                            label="密码" placeholder="密码" :rules="[
                                { required: true, message: '请填写密码' },
                                {
                                    pattern: /^[a-zA-Z0-9]{6,}$/,
                                    message: '密码至少要6位，只能包含字母和数字'
                                }
                            ]" />
                    </van-cell-group>
                    <div class="btn-style">
                        <van-button round block type="primary" native-type="submit">
                            登录
                        </van-button>
                    </div>
                    <div class="link-group">
                        <RouterLink to="/reset" class="link-left">忘记密码</RouterLink>
                        <RouterLink to="/register" class="link-right">注册账号</RouterLink>
                    </div>

                    <!-- 添加其他登录方式 -->
                    <div class="other-login">
                        <div class="divider">
                            <span class="divider-text">其他登录方式</span>
                        </div>
                        <div class="login-methods">
                            <div class="login-method-item">
                                <div class="method-icon wechat">
                                    <van-icon name="wechat" size="24" />
                                </div>
                                <span class="method-text">微信</span>
                            </div>
                            <div class="login-method-item">
                                <div class="method-icon qq">
                                    <van-icon name="qq" size="24" />
                                </div>
                                <span class="method-text">QQ</span>
                            </div>
                            <div class="login-method-item">
                                <div class="method-icon phone">
                                    <van-icon name="phone" size="24" />
                                </div>
                                <span class="method-text">手机</span>
                            </div>
                        </div>
                    </div>

                    <div class="agreement-container">
                        <van-checkbox v-model="checked" class="agreement-checkbox">
                            <span class="agreement-text">
                                我已同意
                                <a href="/terms" class="link">《用户协议》</a>
                                和
                                <a href="/privacy" class="link">《隐私政策》</a>
                            </span>
                        </van-checkbox>
                    </div>
                </van-form>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useUserStore } from '../stores/user';
import { useRouter } from 'vue-router';
import { Checkbox, showToast } from 'vant';
import { showConfirmDialog } from 'vant';

const userStore = useUserStore()
const router = useRouter()

let loginForm = ref({
    userAccount: "",
    userPwd: ""
});

const checked = ref(false);

const handleLogin = async () => {
    // 验证用户名和密码
    if (!loginForm.value.userAccount || !loginForm.value.userPwd) {
        showToast("请输入用户名和密码");
        return;
    }

    // 验证是否同意协议
    if (!checked.value) {
        try {
            // 调整对话框内容与场景匹配
            await showConfirmDialog({
                title: '提示',
                message: '请先同意<a href="/terms" class="dialog-link">《用户协议》</a>和<a href="/privacy" class="dialog-link">《隐私政策》</a>',
                messageType: 'html', // 关键：允许 message 解析 HTML 
                allowHtml: true,
                confirmButtonText: '去同意',
                cancelButtonText: '取消',
            });

            // 用户确认后，可以滚动到协议位置或给出提示
            showToast('请勾选同意协议');
            // 如果需要自动勾选（不推荐，建议用户手动操作）：
            //checked.value = true;
            return;
        } catch (error) {
            // 用户取消后，终止登录流程
            console.log('用户取消了操作');
            return; // 关键：用户取消后不再继续登录
        }
    }

    try {
        const res = await userStore.login(loginForm.value);
        await userStore.getLoginUser();
        router.push({ name: "home" });
    } catch (e) {
        console.log("登录失败原因 ====", e);
        
        // 添加登录失败弹窗提示
        showDialog({
            title: '登录失败',
            message: '用户名或密码错误，请检查后重试',
            confirmButtonText: '重新输入',
            cancelButtonText: '忘记密码',
        }).then(() => {
            // 用户点击"重新输入"，清空密码框
            loginForm.value.userPwd = "";
        }).catch(() => {
            // 用户点击"忘记密码"，跳转到忘记密码页面
            router.push('/reset');
        });
    }
};
const onClickLeft = () => {
    history.back();
};
const onClickRight = () => {
    router.push("/help");
};

// 简单的watch监听路由变化
watch(
    () => router.currentRoute.value,
    (to) => {
        if (to.name === 'login') {
            // 重置表单
            loginForm.value = {
                userAccount: "",
                userPwd: ""
            };
            checked.value = false;
        }
    }
);

</script>

<style lang="scss" scoped>
.login-container {
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: center;
    box-sizing: border-box;

    .login-card {
        width: 100%;
        max-width: 500px;
        height: 100vh;
        display: flex;
        flex-direction: column;

        .login-header {
            /* 关键：父容器设置相对定位，作为子元素绝对定位的参考 */
            position: relative;

            background-image: url("image/login.jpg");
            background-repeat: no-repeat;
            background-size: contain;
            background-position: top;
            background-color: #f0f0f0;
            width: 100%;
            height: 204px;
            display: flex;
            flex-direction: column;

            .login-header-one {
                /* 绝对定位 - 固定在顶部 */
                position: absolute;
                top: 0;
                /* 距离顶部0距离 */
                left: 0;
                /* 距离左侧0距离 */
                width: 100%;
                /* 宽度占满父容器 */
                padding-top: 18px;
                /* 用内边距替代top定位，避免内容溢出 */

                :deep(.van-nav-bar) {
                    background: transparent;

                    &::after {
                        display: none;
                    }

                    .van-nav-bar__content {
                        background: transparent;
                    }

                    .van-nav-bar__arrow,
                    .van-nav-bar__text {
                        color: white;
                    }

                    .van-nav-bar__left {
                        font-size: 15px;
                    }
                }
            }

            .login-header-two {
                /* 绝对定位 - 固定在特定位置 */
                position: absolute;
                top: 20%;
                /* 距离顶部30%位置（可调整） */
                left: 0;
                /* 距离左侧0距离 */
                width: 50%;
                padding: 25px;

                .title {
                    font-size: 20px;
                    color: white;
                    margin-bottom: 10px;
                    font-weight: 600;
                    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
                }

                .subtitle {
                    font-size: 12px;
                    color: white;
                    margin: 0;
                    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
                }
            }
        }

        .login-body {
             margin-top: -31px;
             :deep(.van-nav-bar) {
             border-top-left-radius: 20px;
             border-top-right-radius: 20px;
             }
            .btn-style {
                margin: 16px;
            }

            .link-group {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin: 0 20px 20px;

                .link-left {
                    color: #1677ff;
                    text-decoration: none;
                }

                .link-right {
                    color: #1677ff;
                    text-decoration: none;
                }
            }

            /* 其他登录方式样式 */
            .other-login {
                margin: 20px;

                .divider {
                    position: relative;
                    text-align: center;
                    margin: 20px 0;
                    
                    &::before {
                        content: '';
                        position: absolute;
                        top: 50%;
                        left: 0;
                        right: 0;
                        height: 1px;
                        background: #eee;
                    }

                    .divider-text {
                        background: white;
                        padding: 0 15px;
                        color: #999;
                        font-size: 14px;
                        position: relative;
                    }
                }

                .login-methods {
                    display: flex;
                    justify-content: space-around;
                    align-items: center;

                    .login-method-item {
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                        cursor: pointer;

                        .method-icon {
                            width: 50px;
                            height: 50px;
                            border-radius: 50%;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            margin-bottom: 8px;

                            &.wechat {
                                background: #07c160;
                                color: white;
                            }

                            &.qq {
                                background: #12b7f5;
                                color: white;
                            }

                            &.phone {
                                background: #ff6b35;
                                color: white;
                            }
                        }

                        .method-text {
                            font-size: 12px;
                            color: #666;
                        }
                    }
                }
            }

            .agreement-container {
                position: fixed;
                bottom: 60px;
                left: 20px;
                z-index: 10;
                width: calc(100% - 40px);
            }

            .agreement-checkbox {
                :deep(.van-checkbox__icon) {
                    width: 10px;
                    height: 10px;
                    margin-right: 5px;
                }

                .agreement-text {
                    font-size: 10px;
                    color: #666;

                    .link {
                        color: #1677ff;
                        text-decoration: underline;
                        margin: 0 2px;
                    }
                }
            }
        }
    }
}
</style>
